import React, { useState, useEffect } from 'react';
import { View, TextInput, ScrollView, ActivityIndicator, Text, StyleSheet, Alert, TouchableWithoutFeedback, Image } from 'react-native';
import DateTimePicker, { DateTimePickerEvent } from '@react-native-community/datetimepicker';
import { useNavigation, NavigationProp } from '@react-navigation/native';
import { NativeEventEmitter, NativeModules } from 'react-native';
import { Picker } from '@react-native-picker/picker';
import moment from 'moment';

const SearchHeader: React.FC = () => {
  const searchIcon = require('../assets/app_images/search.png');
  const dateIcon = require('../assets/app_images/calendar.png');
  const selectDownIcon = require('../assets/app_images/select-down.png');

  const [searchType, setSearchType] = useState<string>('全部');
  const [loading, setLoading] = useState(false);
  const [keyword, setKeyword] = useState<string>('');
  const [showPicker, setShowPicker] = useState<boolean>(false);
  const [selectedItemIndex, setSelectedItemIndex] = useState<number>(0);
  const pickerOptions = ['全部', '检测时间', '样品信息', '检测项目'];
  const [chosenDate, setChosenDate] = useState(new Date());
  const [showDatePicker, setShowDatePicker] = useState(false);
  const navigation = useNavigation<NavigationProp<any>>();

  interface ListItem {
    id: number;
    chipnameCN: string;
    kitNo?: string;
    serialNo? : string;
    resultShow?: string;
    sampleNo?: string;
    startTime: string;
    targets: { key?: string; value?: string }[];
  }

  const [dataList, setDataList] = useState<ListItem[]>([]);
  
  // 初始化
  const fetchData = async () => {
    try {
      setLoading(true); // 开始加载数据
      const response = await fetch('http://127.0.0.1:49152/pcrdata/list');
      const data = await response.json();
      if (data.rel === true) {
        const result = data.result;
        // console.log('result', result);
        // 遍历result，将数据转换成前端需要的数据结构, set到dataList中
        const dataList: ListItem[] = [];
        result.forEach((item: any) => {
          const { id, chipnameCN, kitNo, resultShow, sampleNo, serialNo } = item;
          const channel = JSON.parse(item.channel);
          const startTime = moment(parseInt(item.startTime)).format('YYYY-MM-DD');
          const targets: { key?: string; value?: string }[] = [];
          channel.forEach((channelItem: any) => {
            const { channelno, ct, channelname } = channelItem;
            targets[channelno - 1] = { key: channelname, value: ct };
            // 重写这个逻辑
            for (let i = 0; i < 5; i++) {
              if (!targets[i]) {
                targets[i] = {};
              }
            }
          });
          const listItem: ListItem = {
            id,
            chipnameCN,
            kitNo,
            serialNo,
            resultShow,
            sampleNo,
            startTime,
            targets
          };
          dataList.push(listItem);
        });
        setTimeout(() => {
          setLoading(false); 
          setDataList(dataList);
        }, 1000);
      } else {
        Alert.alert('获取数据失败');
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      Alert.alert('获取数据失败', JSON.stringify(error));
    } finally {
      setTimeout(() => {
        setLoading(false);
      }, 1000)
    }
  };


  useEffect(() => {
    fetchData();
  }, []); 
  // 空数组表示effect没有依赖项，只在组件初始化时执行一次
  

  useEffect(() => {
    // 在这里调用fetchData方法，实现组件初始化时获取数据
    const eventEmitter = new NativeEventEmitter(NativeModules.ToastExample);
    const eventListener = eventEmitter.addListener('EventReminder', (event) => {
        const receivedData = JSON.parse(event.eventProperty)
        const data = JSON.parse(receivedData.data);
        const { id, chipnameCN, kitNo, resultShow, sampleNo, serialNo } = data;
        const channel = JSON.parse(data.channel);
        const startTime = moment(parseInt(data.startTime)).format('YYYY-MM-DD');
        const targets: { key?: string; value?: string }[] = [];

        channel.forEach((channelItem: any) => {
          const { channelno, ct, channelname } = channelItem;
          targets[channelno - 1] = { key: channelname, value: ct };
          for (let i = 0; i < 5; i++) {
            if (!targets[i]) {
              targets[i] = {};
            }
          }
        });
        const listItem: ListItem = {
          id,
          chipnameCN,
          kitNo,
          serialNo,
          resultShow,
          sampleNo,
          startTime,
          targets
        };
        setDataList((prevData) => [listItem, ...prevData]);
    });
    return () => {
      eventListener.remove();
    };
  });

  const handleDateChange = (event: DateTimePickerEvent, selectedDate?: Date) => {
    const currentDate = selectedDate || chosenDate;
    setShowDatePicker(false);
    setChosenDate(currentDate);
    setKeyword(currentDate.toISOString().split('T')[0]);
  };

  const handleSearch = async () => {
    // 当切换搜索类型时，需要清空搜索关键字
    if (selectedItemIndex !== 0) {
      setKeyword('');
    }
  
    // 当搜索关键字为空时，需要提示用户输入
    if (keyword === '' && selectedItemIndex !== 0) {
      Alert.alert('请输入搜索关键字');
      return;
    }
  
    // 当seachType为全部时，不需要传递参数 , 为检测时间时，url需要传递startTime参数，为样品信息时，url需要传递sampleNo参数，为检测项目时，url需要传递chipnameCN参数
    let url = '';
    if (selectedItemIndex === 1) {
      const timestamp = new Date(keyword).getTime();
      url = `http://127.0.0.1:49152/selectPcrdata?startTime=${timestamp}`;
    } else if (selectedItemIndex === 2) {
      url = `http://127.0.0.1:49152/selectPcrdata?sampleNo=${keyword}`;
    } else if (selectedItemIndex === 3) {
      url = `http://127.0.0.1:49152/selectPcrdata?chipnameCN=${keyword}`;
    } else {
      fetchData();
      return;
    }
  
    try {
      setLoading(true);
      const response = await fetch(url);
      const data = await response.json();
  
      // 清空 dataList
      setDataList([]);
  
      if (data.rel === true) {
        const result = data.result;
        // 遍历 result，将数据转换成前端需要的数据结构, set 到 dataList 中
        const searchList: ListItem[] = [];
        result.forEach((item: any) => {
          const { id, chipnameCN, kitNo, resultShow, sampleNo, serialNo } = item;
          const channel = JSON.parse(item.channel);
          const startTime = moment(parseInt(item.startTime)).format('YYYY-MM-DD');
          const targets: { key?: string; value?: string }[] = [];
          channel.forEach((channelItem: any) => {
            const { channelno, ct, channelname } = channelItem;
            targets[channelno - 1] = { key: channelname, value: ct };
            // 重写这个逻辑
            for (let i = 0; i < 5; i++) {
              if (!targets[i]) {
                targets[i] = {};
              }
            }
          });
          const listItem: ListItem = {
            id,
            chipnameCN,
            kitNo,
            serialNo,
            resultShow,
            sampleNo,
            startTime,
            targets,
          };
          searchList.push(listItem);
        });
        // 将搜索结果设置到 dataList 中
        setTimeout(() => {
          setLoading(false);
          setDataList(searchList);
        }, 1000);
      } else {
        Alert.alert('获取数据失败');
      }
    } catch (error) {
      console.error('Fetch error:', error);
      Alert.alert('获取数据失败');
    } finally {
      setTimeout(() => {
        setLoading(false);
      }, 1000)
    }
  };
  

  const renderPickerItems = () => {
    return pickerOptions.map((option, index) => (
      <TouchableWithoutFeedback
        key={index}
        onPress={() => {
          setSearchType(option);
          setSelectedItemIndex(index);
          setShowPicker(false);
        }}
      >
        <View style={styles.pickerItem}>
          <View style={styles.triangle} />
          <Text style={styles.modalItem}>{option}</Text>
        </View>
      </TouchableWithoutFeedback>
    ));
  };

  const ListItem: React.FC<{ item: ListItem }> = ({ item }) => {
    const getTargetBackground = (value: string) => {
      return value ? '#FFFFFF' : '#e5e5e5';
    };

    return (
      <TouchableWithoutFeedback onPress={ 
        () => navigation.navigate('Details', { id: item.serialNo })
      }>
        <View style={styles.listItem}>
          <View style={styles.upperSection}>
            <View style={styles.leftBlock}>
              <Text style={styles.nameText} numberOfLines={2} ellipsizeMode="tail">{item.chipnameCN}</Text>
            </View>
            <View style={[styles.rightBlock, { backgroundColor: '#00cfcd' }]}>
              <Text style={styles.dateText}>{item.startTime}</Text>
            </View>
          </View>
          <View style={styles.lowerSection}>
            {item.targets.map((item, index) => (
              <View
                key={index}
                style={[
                  styles.targetBlock,
                ]}>
                <Text style={[styles.targetBlockKey, {backgroundColor: item.key ? '#f7f7f7' : getTargetBackground(item.key || '')}]}>{item.key || '' }</Text>
                <Text style={[styles.targetBlockVal, {backgroundColor: item.value ? '#ffffff' : getTargetBackground(item.value || '')}]}>{item.value || ' '}</Text>
              </View>
            ))}
          </View>
        </View>
      </TouchableWithoutFeedback>
    );
  };

  return (
    <View style={styles.recordScreen}>
      <View style={styles.header}>
        <View style={styles.title}>
          <Text style={styles.titleText}>北京生物医药研究所</Text>
        </View>
        <View style={styles.searchContainerRow}>
          <View style={styles.searchContainer}>
            <TouchableWithoutFeedback  onPress={() => setShowPicker(!showPicker)}>
              <View style={styles.inputWrapper}>
                <Text style={styles.pickerText}>{searchType}</Text>
                <Image source={selectDownIcon}  style={styles.selectDownIcon}/>
              </View>
            </TouchableWithoutFeedback>
            <View style={styles.inputBox}>
             { selectedItemIndex === 1 && (
              <TouchableWithoutFeedback onPress={() => setShowDatePicker(true)}>
                  <View style={styles.dateContainer}>
                    <Image source={dateIcon}  style={styles.dateIcon}/>
                  </View>
              </TouchableWithoutFeedback>
              )}
              <TextInput
                style={styles.input}
                placeholder="输入关键字..."
                placeholderTextColor="#ffffff"
                selectionColor="#ffffff" // 设置光标和选中文本的颜色为红色
                onChangeText={text => setKeyword(text)}
                value={keyword}/>
              <TouchableWithoutFeedback  onPress = {handleSearch}>
                  <View style={styles.searchText}>
                    <Image source={searchIcon}  style={styles.searchIcon} />
                  </View>
              </TouchableWithoutFeedback>
            </View>
          </View>
          {showPicker && (
            <View style={styles.pickerContainer}>
              {renderPickerItems()}
            </View>
          )}
        </View>
      </View>
      {showDatePicker && (
        <DateTimePicker
          testID="dateTimePicker"
          value={chosenDate}
          mode="date" // 设置为 'time' 可以选择时间，设置为 'datetime' 可以选择日期和时间
          is24Hour={true} // 是否使用 24 小时制
          display="default" // 在 Android 上，可以设置为 'spinner' 或 'calendar' 显示样式
          onChange={handleDateChange}
        />
      )}
      {loading ? (
        <ActivityIndicator size="large" color="#00cfcd"  style={styles.activityIndicator}/>
      ) : (
      <ScrollView  style={{ width: "100%", zIndex: 1 }}>
        <View style={styles.listWrapper}>
            {
              dataList.length > 0 ? dataList.map((item, index) => (
                <ListItem
                  key={index}
                  item={item}
                />
              ))
              : 
              <View style={{backgroundColor: '#fff', height: '100%' }}>
                <Text style={{ textAlign: 'center', fontSize: 18, marginTop: 100 }}>暂无数据</Text>
              </View>
            }
        </View>
      </ScrollView>
    )}
    </View>
  );
};

const styles = StyleSheet.create({
  recordScreen : {
    width: '100%',
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    backgroundColor: '#ffffff',
  },
  header: {
    width: '100%',
    height: 200,
    display: 'flex',
    flexDirection: 'column',
    backgroundColor: '#00cfcd',
    zIndex: 100
  },
  title: {
    width: '100%',
    height: 100,
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  },
  titleText:{
    fontSize: 25,
    letterSpacing: 2,
    fontWeight: 'bold',
    color: '#ffffff',
  },
  searchContainerRow: {
    width: '100%',
    height: 100,
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  searchContainer: {
    width: '100%',
    height: 50,
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 5,
    borderWidth: 1,
    borderColor: '#ffffff'
  },

  inputWrapper: {
    width: '22%',
    height: '100%',
    display: 'flex',
    borderTopLeftRadius: 5,
    borderBottomLeftRadius: 5,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff'
  },

  pickerText: {
    color: 'black',
    fontSize: 12
  },

  selectDownIcon : {
    width: 8,
    height: 5,
    marginLeft: 3
  },

  inputBox:{
    flex: 1,
    height: '100%',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },

  input: {
    flex : 1,
    padding: 5,
    color: '#ffffff'
  },
  dateContainer: {
    width: 32,
    height: '100%',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  dateIcon: {
    width: 16,
    height: 16,
    zIndex: 100
  },

  searchText: {
    width: 50,
    height: '100%',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    borderLeftWidth: 1,
    borderLeftColor: '#ffffff'
  },

  searchIcon: {
    width: 20,
    height: 20,
  },

  pickerContainer: {
    width: '22%',
    position: 'absolute',
    top: 80, // 调整距离输入框的位置
    left: 20, // 调整距离屏幕左侧的位置
    backgroundColor: '#ffffff',
    borderRadius: 5,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 1.84,
    elevation: 5,
    zIndex: 10000000000
  },
  pickerItem: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'relative',
  },
  modalItem: {
    width: '100%',
    paddingVertical: 10,
    fontSize: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f6f6f6',
    paddingHorizontal: 10,
  },
  triangle: {
    width: 0,
    height: 0,
    backgroundColor: 'transparent',
    borderStyle: 'solid',
    borderLeftWidth: 5,
    borderRightWidth: 5,
    borderBottomWidth: 8,
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent',
    borderBottomColor: '#ffffff',
    position: 'absolute',
    top: -8,
    left: '50%',
    marginLeft: -5,
  },

  listWrapper : {
    width: '100%',
    height: '100%',
    marginTop: 0,
    marginBottom: 20,
    display: 'flex',
    flexDirection: 'column',
    backgroundColor: '#f7f7f7'
  },

  listItem: {
    width: '96%',
    marginLeft: '2%',
    paddingBottom: 12,
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
    elevation: 3,
    marginTop: 15,
    backgroundColor: '#FFF',
  },

  upperSection: {
    width: '100%',
    height: 55,
    flexDirection: 'row',
    marginBottom: 10
  },
  leftBlock: {
    flex: 1,
    paddingTop: 5,
    paddingLeft: 15,
    paddingRight: 10,
    borderBottomColor: '#f2f2f2',
    borderBottomWidth: 1
  },
  nameText: {
    color: '#02a2f9',
    fontSize: 14
  },
  rightBlock: {
    width: 90,
    backgroundColor: '#00cfcd',
    height: '100%',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    borderTopRightRadius: 10,
    borderBottomColor: '#f2f2f2',
    borderBottomWidth: 1
  },
  dateText: {
    color: '#FFF',
    fontSize: 14,
  },
  lowerSection: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '94%',
    marginLeft: '3%'
  },
  targetBlock: {
    width: '20%',
    height: 70,
    borderRightColor: '#f2f2f2',
    borderRightWidth: 1
  }, 
  targetBlockKey:{
    // backgroundColor: '#f7f7f7',
    height:35,
    textAlign: 'center',
    lineHeight: 35,
    fontSize: 12
  },
  targetBlockVal:{
    // backgroundColor: '#FFFFFF',
    height: 35,
    textAlign: 'center',
    lineHeight: 35,
    borderBottomColor: '#f2f2f2',
    borderBottomWidth: 1,
    fontSize: 12
  },
  activityIndicator : {
    width: '100%',
    height: '100%',
    position: 'absolute',
    top: 60,
    left: 0,
    zIndex: 99999
  }
});

export default SearchHeader;

